#include "Memory.h"

mem::CMemory::CMemory()
{
}

mem::CMemory::~CMemory()
{
}

bool mem::CMemory::AddSignature(const char *name, const char *module, const unsigned char *signature, const char *mask, long offset)
{
	HMODULE hmod = GetModuleHandleA(module);
	if(!hmod)
	{
		return false;
	}

	MODULEINFO modinfo = {0};
	if(!GetModuleInformation(GetCurrentProcess(), hmod, &modinfo, sizeof(MODULEINFO)))
	{
		return false;
	}

	byte* address = mem::util::FindPattern(reinterpret_cast<unsigned char*>(hmod),
		modinfo.SizeOfImage,
		signature,
		mask);

	if(address == NULL)
	{
		MessageBox(NULL, name, "Unable to locate!", NULL);
		std::cout<<"Could not find signature: "<<name<<std::endl;
		return false;
	}

	this->AddressMap[name] = address + offset;

	return true;
}

byte* mem::CMemory::GetAddress(const char *name)
{
	return this->AddressMap[name];
}


inline byte* mem::util::FindPattern(unsigned char *address, unsigned int size, const unsigned char *signature, const char *mask)
{
    for(unsigned int i = 0; i < size; i++ )
    {
        if(DataCompare(reinterpret_cast<unsigned char*>(address + i), signature, mask))
            return (byte*)(address + i);
    }
    return 0;
}

inline bool mem::util::DataCompare(const unsigned char *data, const unsigned char *signature, const char *mask)
{
    for(; *mask; ++mask, ++data, ++signature)
        if(*mask == 'x' && *data != *signature)
            return false;

    return *mask == 0;
}